/**
 * Copyright (C) 2013 The yydorid-framework project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.yangying.androidframework.core.adapter;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;

import net.yangying.androidframework.R;
import net.yangying.androidframework.core.model.AppImage;
import net.yangying.androidframework.util.MD5Utils;
import net.yangying.androidframework.util.RemoteResourceManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

/**
 * @author YANGYING
 * @date 2011-6-12
 */
public class AppImageListAdapter extends BaseGroupAdapter<AppImage> implements ObservableAdapter {

	private static final String TAG = AppImageListAdapter.class.getSimpleName();

    private LayoutInflater mInflater;
    private int mLayoutToInflate;
    private RemoteResourceManager mRrm;
    private RemoteResourceManagerObserver mResourcesObserver;
    private Handler mHandler = new Handler();

    private Set<String> mLaunchedPhotoFetches;
    private HashMap<String,Bitmap> map;
    
    Bitmap bmp_default=null;
//  Bitmap bmp_default_corner=null;

    public AppImageListAdapter(Context context, RemoteResourceManager rrm) {
        super(context);
        mInflater = LayoutInflater.from(context);
        mLayoutToInflate = R.layout.app_image_list_item;
        mRrm = rrm;
        mResourcesObserver = new RemoteResourceManagerObserver();
        mLaunchedPhotoFetches = new HashSet<String>();
        map = new HashMap<String,Bitmap>();
        mRrm.addObserver(mResourcesObserver);
        bmp_default=BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
//        bmp_default_corner=BitmapUtils.getRCB(bmp_default, 8);
    }

    public AppImageListAdapter(Context context, int layoutResource) {
        super(context);
        mInflater = LayoutInflater.from(context);
        mLayoutToInflate = layoutResource;
    }

    @Override
    public void removeObserver() {
        mHandler.removeCallbacks(mUpdatePhoto);
        mRrm.deleteObserver(mResourcesObserver);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // A ViewHolder keeps references to children views to avoid unnecessary
        // calls to findViewById() on each row.
        ViewHolder holder;

        // When convertView is not null, we can reuse it directly, there is no
        // need to re-inflate it. We only inflate a new View when the
        // convertView supplied by ListView is null.
        if (convertView == null) {
            convertView = mInflater.inflate(mLayoutToInflate, null);

            // Creates a ViewHolder and store references to the two children
            // views we want to bind data to.
            holder = new ViewHolder();
            holder.img = (ImageView)convertView.findViewById(R.id.iv_appBigImageListImage);
//            holder.name = (TextView) convertView.findViewById(R.id.tv_appListItemName);
//            holder.desc = (TextView) convertView.findViewById(R.id.tv_appListItemDesc);
            convertView.setTag(holder);
        } else {
            // Get the ViewHolder back to get fast access to the TextView
            // and the ImageView.
            holder = (ViewHolder) convertView.getTag();
        }

        AppImage appImage = (AppImage) getItem(position);
        Uri photoUri = null;
        if (appImage.getImgUrl() != null) 
        {
        	String imgurlmd5 = MD5Utils.md5(appImage.getImgUrl());
        	if(!map.containsKey(imgurlmd5)) //appImage.getId()
            {
                try {
                    photoUri = Uri.parse(appImage.getImgUrl());
                    InputStream is=mRrm.getInputStream(photoUri);
                    Bitmap bitmap=null;
//                    Bitmap bitmap_corner=null;
                    if(is!=null){
                        bitmap = BitmapFactory.decodeStream(is);
                        if(bitmap!=null){
//                            bitmap_corner=BitmapUtils.getRCB(bitmap, 8);
                            holder.img.setImageBitmap(bitmap);
                            if(!map.containsKey(imgurlmd5))
                                map.put(imgurlmd5, bitmap);
                        }
                        else{
                        	holder.img.setImageBitmap(bmp_default);
                        }
                    }
                    else {
                    	holder.img.setImageBitmap(bmp_default);
                    }
                } catch (IOException e) {
                	holder.img.setImageBitmap(bmp_default);
                    if (!mLaunchedPhotoFetches.contains(imgurlmd5)) {
                        mLaunchedPhotoFetches.add(imgurlmd5);
                        mRrm.request(photoUri);
                    }
                } catch(Exception e)
                {
                	holder.img.setImageBitmap(bmp_default);
                }         		
            } else {
            	Bitmap bitmap=null;
                bitmap=map.get(imgurlmd5);
                if(bitmap!=null){
                	holder.img.setImageBitmap(bitmap);
                }
                else{
                	holder.img.setImageBitmap(bmp_default);
                }
            }

        } else {
        	holder.img.setImageBitmap(bmp_default);
        }

//        holder.name.setText(app.getName());
//        holder.desc.setText(app.getDesc());
        return convertView;
    }

    // public void removeItem(int position) throws IndexOutOfBoundsException {
    // group.remove(position);
    // notifyDataSetInvalidated();
    // }

    private class RemoteResourceManagerObserver implements Observer {
        @Override
        public void update(Observable observable, Object data) {
            mHandler.post(mUpdatePhoto);
        }
    }

    private Runnable mUpdatePhoto = new Runnable() {
        @Override
        public void run() {
            notifyDataSetChanged();
        }
    };

    static class ViewHolder {
        ImageView img;
//        TextView name;
//        TextView desc;
    }
}
